package li.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import li.entity.Book;
import li.entity.User;
import li.idao.IBookDao;
import li.idao.IUserDao;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class HomeService {

	@Resource
	private IBookDao bookDao;
	@Resource
	private IUserDao userDao;

	public Book findOneBook(long id) {
		return bookDao.findOneById(id);
	}

	public User ValidateUser(String username, String password) {
		return userDao.findOne(username, password);
	}

	public Set<Book> findUserBooks(long id) {
		return userDao.findUserBooks(id);
	}

	public void returnBook(long id, User u) {
		Book b = bookDao.findBookById(id);
		bookDao.returnBook(b);
		u.getBooks().remove(b);
		for (Book book : u.getBooks()) {
			if (book.getId() == b.getId()) {
				u.getBooks().remove(book);
				break;
			}
		}
	}

	public void borrowBook(long id, User u) {
		// TODO Auto-generated method stub
		Book b = bookDao.findBookById(id);

		SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
		Date d = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		// 借书时间为1个月
		c.add(Calendar.MONTH, 1);
		Date d2 = c.getTime();
		b.setBorrowDate(format.format(d));
		b.setReturnDate(format.format(d2));
		b.setUser(u);
		b.setBorrowed(true);
		b.setBorrowNum(b.getBorrowNum() + 1);
		u.getBooks().add(b);
		bookDao.borrowBook(b);
	}

	public void createNewUser(String username, String password, String stuId) {
		User u = new User();
		u.setPassword(password);
		u.setUsername(username);
		u.setStuId(stuId);
		userDao.create(u);
	}

	public List<Book> findHotBooks() {
		final int TOPN = 3; // 最热3本
		return bookDao.findHotBooks(TOPN);
	}
}
